<template>
  <div v-if="!printShow">
    <div class="front">
      <el-collapse v-model="activeNames" class="front-collapse"
        @change="activeNames = !activeNames; collapseName == '收起' ? collapseName = '展开' : collapseName = '收起'">
        <el-collapse-item :title="collapseName" class="collapse-1" name="1">
          <el-form :model="searchForm" label-width="120px">
            <el-form-item label="入库单号" class="front-input">
              <el-input v-model="searchForm.orderCode" />
            </el-form-item>
            <el-form-item label="货品编码" class="front-input">
              <el-input v-model="searchForm.jadeCode" />
            </el-form-item>
            <el-form-item label="所属仓库" class="front-input">
              <el-select v-model="searchForm.warehouseId" placeholder="搜索匹配" style="">
                <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName" :value="item.warehouseId" />
              </el-select>
            </el-form-item>
            <el-form-item label="供应商" class="front-input">
              <el-select v-model="searchForm.supplierId" placeholder="搜索匹配" style="" prop="supplierId">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSearch">查询</el-button>
              <el-button type="primary" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </div>

    <div class="tail">
      <div class="tail-action">
        <el-button type="primary">导出明细</el-button>
        <el-button type="primary" @click="printSelectedRows">直接打印明细</el-button>
        <el-button type="primary" @click="designPrint">自定义打印明细</el-button>
        <el-popover placement="bottom" trigger="click">
          <template #reference>
            <el-button><el-icon>
                <List />
              </el-icon>显示设置</el-button>
          </template>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
            <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
          </el-checkbox-group>
        </el-popover>
      </div>
      <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 450 : 660" v-loading="tableLoading" @selection-change="handleChangeSelection">
        <template v-slot:empty>
          <div class="no-data">暂无数据</div>
        </template>
        <el-table-column type="selection" width="40" />
        <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
          :max-width="item.maxWidth" :label="item.label">
          <template v-if="true" v-slot:default="scope">
            <div v-if="item.prop == 'orderType'">
              <el-tag v-if="scope.row[item.prop] == 0" type="success">采购入库</el-tag>
              <el-tag v-else-if="scope.row[item.prop] == 1" type="info">借货入库</el-tag>
            </div>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="printTag(scope.row)">打印标签</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination" style="float: right; margin-top: 15px;">
        <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
          layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <div class="dialog-list">
      <div>
        <el-drawer v-model="drawer" :direction="direction" size="35%">
          <el-descriptions border size="large" direction="vertical" title="入库单详情">
            <el-descriptions-item label="入库单号">{{ rowDetails.orderCode }}</el-descriptions-item>
            <el-descriptions-item label="数量">{{ rowDetails.jadeWeight }}</el-descriptions-item>
            <el-descriptions-item label="供应商" width="150">{{ rowDetails.supplierName }}</el-descriptions-item>
            <el-descriptions-item label="客户名字">{{ rowDetails.clientName }}</el-descriptions-item>
            <el-descriptions-item label="仓位名字" width="150">{{ rowDetails.storageName }}</el-descriptions-item>
            <el-descriptions-item label="仓库名字">{{ rowDetails.warehouseName }}</el-descriptions-item>
            <el-descriptions-item label="入库时间">{{ rowDetails.createTime }}</el-descriptions-item>
            <el-descriptions-item label="添加人">{{ rowDetails.createBy }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ rowDetails.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="修改人">{{ rowDetails.updateBy }}</el-descriptions-item>
          </el-descriptions>
        </el-drawer>
      </div>
    </div>
  </div>
  <div v-else>
    <a-button @click="printShow = false" type="primary" danger>退出打印页面</a-button>
    <print :provider="providerData" :printData="printDataProp"></print>
  </div>
</template>
    
<script>
import { defineComponent, reactive, toRefs, ref } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { getInJadeList } from '@/api/inbound/inbound'
import { getWarehouseListV2 } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { List } from '@element-plus/icons-vue';
//打印界面
import print from '@/print/index.vue'
//打印标签组成
import provider from '@/api/inbound/goods/goodsProvider.js'
import { createElementTypes, printData } from '@/api/inbound/goods/goodsProvider.js'
export default defineComponent({
  name: "HomeView",
  components: {
    List,
    print
  },
  setup() {
    //将打印标签界面传给print子组件
    const providerData = ref(provider)
    const printDataProp = ref(printData)
    const printShow = ref(false)

    const rowDetails = ref({})

    const drawer = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)//显示设置是否全选
    const searchForm = reactive({  //入库查询表单数据
      jadeBarcode: '',
      jadeCode:'',
      orderCode: '',
      warehouseId: '',
      supplierId: '',
    })
    const inboundJadeData = ref([])
    const selectedFilters = ref([])
    const selectedRows = ref([])//已勾选记录
    const inboundDataColumn = ref([])//表头数据
    const supplierList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([
      { label: '入库单编号', prop: 'inboundOrderCode', width: '120', isdisabled: true, isSelected: true },
      { label: '入库类型', prop: 'orderType', width: '120', isdisabled: true, isSelected: true },
      { label: '仓库编码', prop: 'warehouseCode', width: '120', isdisabled: true, isSelected: true },
      { label: '仓库名称', prop: 'warehouseName', width: '120', isdisabled: true, isSelected: true },
      { label: '入库仓位编码', prop: 'storageCode', width: '140', isdisabled: true, isSelected: true },
      { label: '入库仓位名称', prop: 'storageName', width: '140', isdisabled: true, isSelected: true },
      // { label: '翡翠信息ID', prop: 'jadeId', width: '100', isdisabled: true, isSelected: true },
      // { label: '翡翠品类ID', prop: 'jadeTypeId', width: '100', isdisabled: true, isSelected: true },
      { label: '翡翠品类', prop: 'jadeTypeName', width: '140', isdisabled: true, isSelected: true },
      { label: '翡翠编码', prop: 'jadeCode', width: '140', isdisabled: true, isSelected: true },
      { label: '翡翠名称', prop: 'jadeName', width: '130', isdisabled: true, isSelected: true },
      { label: '翡翠条码', prop: 'jadeBarcode', width: '130', isdisabled: true, isSelected: true },
      { label: '成本价格', prop: 'jadeCost', width: '100', isdisabled: true, isSelected: true },
      { label: '标签价格', prop: 'jadeTagPrice', width: '100', isdisabled: true, isSelected: true },
      { label: '成本价暗码', prop: 'jadeCostCipher', width: '100', isdisabled: true, isSelected: true },
      { label: '标签价暗码', prop: 'jadeTagPriceCipher', width: '100', isdisabled: true, isSelected: true },
      // { label: '翡翠图片ID', prop: 'imageId', width: '100', isdisabled: true, isSelected: true },
      { label: '备注', prop: 'remark', width: '200', isdisabled: true, isSelected: true },
      { label: '入库人员', prop: 'createBy', width: '100', isdisabled: true, isSelected: true },
      { label: '入库时间', prop: 'createTime', width: '200', isdisabled: true, isSelected: true },
    ])

    const collapseName = ref('展开');
    const activeNames = ref(false)

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeData.value.length,
      }
    });

    // loading
    const tableLoading = ref(true)
    const tableData = () => {
      return inboundJadeData.value
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = (page, limit) => {//获取入库单列表
      tableLoading.value = true
      const params = {
        pageNum: page,
        pageSize: limit
      }
      getInJadeList(params).then((res) => {
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }

    }
    const handleCheckChange = (val) => {//勾选列
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    onBeforeMount(() => {
      getSupplierList().then((res) => {
        supplierList.value = res.rows
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res
      })
      handleGetInboundOrderList(state.data.page, state.data.limit)
    })
    const printSelectedRows = () => {//打印入库单货品明细
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title></head><body>`
        content += `<h1>入库货品明细</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;">`;
        content += `<tr>
            <th style="border: 1px solid black; padding: 8px;">入库单单号</th>
            <th style="border: 1px solid black; padding: 8px;">数量</th>
            <th style="border: 1px solid black; padding: 8px;">入库时间</th>
            <th style="border: 1px solid black; padding: 8px;">供应商</th>
            <th style="border: 1px solid black; padding: 8px;">入库仓库</th>
            <th style="border: 1px solid black; padding: 8px;">入库人员</th>
          </tr>`;
        selectedRows.value.forEach(row => {
          content += `<tr>
              <td style="border: 1px solid black; padding: 8px;">${row.orderCode}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.jadeQuantity}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.supplierName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.warehouseName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createBy}</td>
            </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.print()
        printWindow.onload = () => {
          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }

    //自定义打印入库单
    const designPrint = () => {
      console.log("这是provider:",provider)
      // 需要一次数据更新
      printDataProp.value = printData
      printShow.value = true;
    }

    onMounted(() => {
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })
    const mergeOrder = () => {

    }
    const onSearch = () => {
      const params = {
        pageSize: state.data.limit,
        pageNum: state.data.page,
        orderCode: searchForm.orderCode,
        jadeCode: searchForm.jadeCode,
        supplierId: searchForm.supplierId,
        warehouseId: searchForm.warehouseId
      }
      getInJadeList(params).then((res) => {
        inboundJadeData.value = res.rows
        state.data.total = res.total
        tableLoading.value = false
      })
    }

    const openDetails = (row) => { //删除仓位
      drawer.value = true
      rowDetails.value = row
    }
    const printTag = (row) => { //打印标签
      drawer.value = true
      rowDetails.value = row
    }
    const handleChangeSelection = (selection) => {//已勾选的记录
      selectedRows.value = selection
      // console.log(selectedRows)
      createElementTypes(selectedRows._rawValue)
      console.log(printData)
    }
    const onReset=()=>{
      searchForm.jadeCode=searchForm.orderCode=searchForm.supplierId=searchForm.warehouseId=''
    }

    return {
      printShow,providerData,printDataProp,designPrint,//打印的相关变量及方法
      inboundJadeData,
      searchForm, rowDetails, drawer,
      collapseName, warehouseList, supplierList,
      activeNames,
      inboundDataColumn, selectedFilters, tableFilter, checkAll, isIndeterminate,
      tableData, mergeOrder, openDetails, printTag, printSelectedRows, handleChangeSelection,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,
      handleGetInboundOrderList, onSearch,onReset,tableLoading,
      ...toRefs(state),
    };
  },
});


</script>
    #F8F8F8
    
<style rel="stylesheet/scss" lang="scss" scoped>
.front {
  background-color: #FFF;
  padding: 10px;

  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 10px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>
    